﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using EncryptionServer.Message;
using System.Net.Sockets;
using System.Net;
using System.Configuration;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.Cryptography;
using System.Management;
using System.ServiceModel;

using EncryptionServer.DogHelper;
using MODEL;
using BLL;
using EncryptionServer.WS;
using EncryptionServer.CrcCheck;
using COM;
using System.Diagnostics;
using ServiceImpl;



namespace EncryptionServer
{
    public delegate void RefreshSetHander();
    public partial class FrmMain : Form
    {

        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);

        WebServiceSoapClient webMethod = new WebServiceSoapClient();

        Dog dog;
        bool off = false;
        byte[] dogCode = new byte[8];
        WorkShopInfo wsInfo = null;

        private BordBLL boardBLL = new BordBLL();
        private picMakeUpBLL picBLL = new picMakeUpBLL();

        public static string strDogCode = string.Empty;//加密狗的编码，用于加解密
        public static Mutex dogMutex;//读写狗的互斥体

        Thread thSendMessage;
        SocketMethod skMethod;
        private delegate void socketDelegate();
        //PhotoMove.FrmPhotoMove frmPhoto = null;
        PhotoMove.FrmNewMoveFile frmPhoto = null;
        FrmCRCCheck frmCRCCheck = null;

        ShopAndProductTempleteService prodctTempleHost;
        OrderBLL _orderBLL = new OrderBLL();
        public FrmMain()
        {
            InitializeComponent();
            this.Hide();
            this.Visible = false;
            try
            {
               // MessageBox.Show("获取加密狗信息");
                dog = Dog.GetInstance;
                //WriteLogForCheck.WriteLogFile(DateTime.Now + ":获取加密信息");

                SocketMethod.strEnWebDogCode = GetENWebdogcode();
                
                //获得加密狗编号
                dog.GetDogCode(out dogCode);
                //WriteLogForCheck.WriteLogFile("1111:" + SocketMethod.strEnWebDogCode);
                //WriteLogForCheck.WriteLogFile("2222:" + dogCode.ToString());
                if (string.IsNullOrEmpty(SocketMethod.strEnWebDogCode) || dogCode.Length <= 0)
                {
                    MessageBox.Show("获取加密狗信息失败！");
                    Environment.Exit(0);
                }
                //MessageBox.Show("获取加密狗编号成功");
                try
                {
                   //// wsInfo = webMethod.GetWorkShopInfo(dogCode);
                   // if (wsInfo == null)
                   // {
                   //     MessageBox.Show("初次使用加密狗请连接外网，请确认连接到外网");
                   //     Environment.Exit(0);
                   // }
                    //MessageBox.Show("加密狗信息获取成功");
                }
                catch { }//连不上webservice时会报异常
            }
            catch (Exception)
            {
                MessageBox.Show("加密狗信息不正确，程序即将退出2，请联系管理员");
                Environment.Exit(0);
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UDPMessage.CustomerName = "";
            //MessageBox.Show("开始初始化窗体");
            //同步本机时间
            //WriteLogForCheck.WriteLogFile(DateTime.Now + ":修改本地时间");

          //  SetLocalTime();
            //检查exe文件MD5码
         //   WriteLogForCheck.WriteLogFile(DateTime.Now + ":检查exe文件MD5码");

         //   CheckExeMD5OnLoadForm();
            //检查是否回调日期
          //  CheckDateOnLoadForm();
            //检查网卡MAC地址
          //  CheckNetCardMacAddressOnFormLoad();
            //写加密字符串
            WriteLogForCheck.WriteLogFile(DateTime.Now + ":写加密字符串");

            WritePwdStr();
            //启动NetTcpShareServer
            WriteLogForCheck.WriteLogFile(DateTime.Now + ":NetTcpShareServer");

            StartUPNetTcpShareServer();
            WriteLogForCheck.WriteLogFile(DateTime.Now + ":启动移动照片");

            //启动移动照片
            ////frmPhoto = new EncryptionServer.PhotoMove.FrmPhotoMove();
            frmPhoto = new EncryptionServer.PhotoMove.FrmNewMoveFile();
            frmPhoto.UserId = 2;
            frmPhoto.Show();
            frmPhoto.Visible = false;
            frmPhoto.Hide();
            try
            {
                List<ServiceHost> hosts = new List<ServiceHost>();
                hosts.Add(new ServiceHost(typeof(FilesService)));
                 prodctTempleHost = new ShopAndProductTempleteService();
                hosts.Add(new ServiceHost(prodctTempleHost));
                hosts.ForEach(host => host.Open());

                bwProductTemplete.RunWorkerAsync();
                //Console.WriteLine("All services are started...");
                //Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误信息是:" + ex.ToString());
            }


            //启动开单照片CRC校验
            frmCRCCheck = new FrmCRCCheck();
            frmCRCCheck.Show();
            frmCRCCheck.Visible = false;
            frmCRCCheck.Hide();

            //发送连接字符串
            thSendMessage = new Thread(new ThreadStart(SendMessage));
            thSendMessage.IsBackground = true;

            skMethod = new SocketMethod();
            socketDelegate dlsk = new socketDelegate(skMethod.DecSocket);
            dlsk.BeginInvoke(null, null);


            int dogNum;
            dogNum = dog.GetDogNum();
            if (dogNum > 0)
            {
                thSendMessage.Start();
            }
            else
            {
                MessageBox.Show("没有找到加密狗", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                notifyIcon1.Visible = false;
                Environment.Exit(0);
            }
            //获取软件最后到期时间
            GetLastDate();
            ShowSetInfo();
        }


        private void tsProgramUpdate_Click(object sender, EventArgs e)
        {
            FrmUpdate frmUpdate = new FrmUpdate();
            frmUpdate.ShowDialog();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (!Program._serverChange && !Program._notFoundDog)
                {
                    e.Cancel = true;
                    this.Hide();
                }
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

        private void 显示程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("这是服务器程序，确定退出吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                notifyIcon1.Visible = false;
                if(frmPhoto!=null)
                    frmPhoto.notifyIcon1.Visible = false;
                Environment.Exit(0);
            }
        }

        private void SendMessage()
        {
            while (true)
            {
                try
                {
                    UDPMessage.SendMessage();
                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    if (ex is SocketException)
                    {
                        Thread.Sleep(500);
                    }
                }
            }
        }
        /// <summary>
        /// 获得当天加密狗密文
        /// </summary>
        /// <returns></returns>
        private string GetENWebdogcode()
        {
            string enWebdogcode;
            DateTime dt = DateTime.Now;
            try
            {

                //dt = webMethod.GetDate();
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + dt.ToShortDateString());

            }
            catch { }
            //string dtstr = new string(dt.GetDateTimeFormats()[3].ToCharArray().Reverse().ToArray());
            DateTime dateTime=DateTime.Now.AddDays(300);
            string dtstr = new string(dateTime.ToShortDateString().ToCharArray().Reverse().ToArray());
            WriteLogForCheck.WriteLogFile(DateTime.Now+":" + dtstr);

            dtstr = dtstr.Replace("-", "");
            string errMes = "";
            dog.GetEnWebDogCodeByData(dtstr, out enWebdogcode, out  errMes);
            WriteLogForCheck.WriteLogFile("local:" + errMes);
            return enWebdogcode;
        }
        /// <summary>
        /// 同步电脑时间，并写日期文件
        /// </summary>
        private void SetLocalTime()
        {
            DateTime dtweb = DateTime.Now;
            try
            {
                dtweb = webMethod.GetDate();

            }
            catch { }
            SystemTime systemTime = new SystemTime();
            systemTime.wDay = (ushort)dtweb.Day;
            systemTime.wDayOfWeek = (ushort)dtweb.DayOfWeek;
            systemTime.wHour = (ushort)dtweb.Hour;
            systemTime.wMiliseconds = (ushort)dtweb.Millisecond;
            systemTime.wMinute = (ushort)dtweb.Minute;
            systemTime.wMonth = (ushort)dtweb.Month;
            systemTime.wSecond = (ushort)dtweb.Second;
            systemTime.wYear = (ushort)dtweb.Year;
            try
            {
                SetLocalTime(ref systemTime);
                dog.WriteDateFile(dtweb);
            }
            catch (Exception ex)
            {
                WriteLogForCheck.WriteLogFile("同步系统时间错误：" + " " + ex.Message);
            }

        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMiliseconds;
        }

        /// <summary>
        /// 检查程序MD5码(加载主窗体时运行)
        /// </summary>
        private void CheckExeMD5OnLoadForm()
        {
            string currentMD5 = GetEXEFileHash();
            string preMd5 = dog.ReadEXEMD5File();
            if (currentMD5 != preMd5)
            {
                bool update = false;

                try
                {
                    update = webMethod.UpdateMD5(dogCode);
                }
                catch
                {
                    WriteLogForCheck.WriteLogFile("检查MD5更新标志时，外网连接错误" + DateTime.Now.ToString());
                }
                //if (update)
                //{
                //    dog.WriteEXEMD5File(Encoding.ASCII.GetBytes(currentMD5));
                //    webMethod.SetOffUpdateMD5(dogCode);

                //}
                //else
                //{
                //    MessageBox.Show("程序被恶意修改，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    Environment.Exit(0);
                //}

            }
        }

        public void StartUPNetTcpShareServer()
        {
            string serverErrorStr = "";
            int serverStatus = GetWindowsServiceStartType("NetTcpPortSharing", out serverErrorStr);
            if (serverStatus == 4)
            {
                if (SetWindowsServiceStartType("NetTcpPortSharing", 2))
                {

                }
                else
                {
                    MessageBox.Show("无法更改服务NetTcpPortSharing的启动类型，请手动修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //

                    Environment.Exit(1);
                }
            }
            else if (serverStatus == -1)
            {
                MessageBox.Show("无法更改服务NetTcpPortSharing的启动类型，请手动修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //

                
            }
            else
            {

            }
        }    //取得服务的启动类型的当前状态，返回启动类型的状态値
        //2：自动，3：手动，4：禁用 ......
        //sServiceName服务名称
        //sState输出相关的状态代码，失败则为错误消息
        static int GetWindowsServiceStartType(String sServiceName, out String sState)
        {
            sState = "";

            try
            {
                System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo();

                objProcessInf.FileName = "cmd.exe";

                objProcessInf.UseShellExecute = false;

                objProcessInf.RedirectStandardError = true;
                objProcessInf.RedirectStandardInput = true;
                objProcessInf.RedirectStandardOutput = true;

                objProcessInf.CreateNoWindow = true;

                objProcessInf.Arguments = "/c sc qc " + sServiceName;

                System.Diagnostics.Process objProcess = System.Diagnostics.Process.Start(objProcessInf);

                String sStateValue = objProcess.StandardOutput.ReadToEnd();

                if (sStateValue.IndexOf("AUTO_START") > 0)
                {
                    sState = "AUTO_START";
                    return 2;
                }

                if (sStateValue.IndexOf("DEMAND_START") > 0)
                {
                    sState = "DEMAND_START";
                    return 3;
                }

                if (sStateValue.IndexOf("DISABLED") > 0)
                {
                    sState = "DISABLED";
                    return 4;
                }

                return 0;

            }
            catch (Exception e)
            {
                sState = e.Message;
                return -1;
            }
        }
        //设置服务的启动类型
        //sServiceName服务名称
        //iStartType要设置的启动类型
        //返回成功状态 true：成功，false：失败
        static Boolean SetWindowsServiceStartType(String sServiceName, int iStartType)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo();

                objProcessInf.FileName = "cmd.exe";

                objProcessInf.CreateNoWindow = false;
                objProcessInf.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                string sStartState = "boot";

                switch (iStartType)
                {
                    case 1:
                        {
                            sStartState = "system";
                            break;
                        }
                    case 2:
                        {
                            sStartState = "auto";
                            break;
                        }
                    case 3:
                        {
                            sStartState = "demand";
                            break;
                        }
                    case 4:
                        {
                            sStartState = "disabled";
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }

                objProcessInf.Arguments = "/c sc config " + sServiceName + " start= " + sStartState;

                System.Diagnostics.Process.Start(objProcessInf);

                return true;
            }
            catch
            {
                return false;
            }
        } 
        /// <summary>
        /// 定时检查exe文件MD5码
        /// </summary>
        private void CheckExeMD5()
        {
            //string currentMD5 = GetEXEFileHash();
            //string preMd5 = dog.ReadEXEMD5File();
            //if (currentMD5 != preMd5)
            //{
            //    if (DateTime.Now.Day != 25)
            //    {
            //        bool update = false;

            //        try
            //        {
            //            update = webMethod.UpdateMD5(dogCode);
            //        }
            //        catch
            //        {
            //            WriteLogForCheck.WriteLogFile("检查MD5更新标志时，外网连接错误" + DateTime.Now.ToString());
            //        }
            //        if (update)
            //        {
            //            dog.WriteEXEMD5File(Encoding.ASCII.GetBytes(currentMD5));
            //            webMethod.SetOffUpdateMD5(dogCode);

            //        }
            //        else
            //        {
            //            MessageBox.Show("程序被恶意修改，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //            Environment.Exit(0);
            //        }

            //    }
            //}
        }

        /// <summary>
        /// 获取EXE文件MD5码
        /// </summary>
        /// <returns></returns>
        private string GetEXEFileHash()
        {
            return GetFileHash(Application.ExecutablePath);
        }
        /// <summary>
        /// 获得文件的MD5码
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private string GetFileHash(string filePath)
        {
            string sResult = "";

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] result = md5.ComputeHash(fs);
                fs.Close();
                sResult = BitConverter.ToString(result);
                sResult = sResult.Replace("-", "");
            }
            return sResult;

        }

        /// <summary>
        /// 加载主窗体时检查日期
        /// </summary>
        private void CheckDateOnLoadForm()
        {
            DateTime dtPc = Convert.ToDateTime(DateTime.Now.GetDateTimeFormats()[3]);
            DateTime dtfile = dog.ReadDateFile();
            if (dtfile > dtPc)
            {
                MessageBox.Show("电脑时间不正确，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(0);
            }

        }
        /// <summary>
        /// 定时检查电脑日期
        /// </summary>
        private void CheckDate()
        {
            if (DateTime.Now.Day == 25)
            {
                off = true;
            }
            DateTime dtPc = Convert.ToDateTime(DateTime.Now.GetDateTimeFormats()[3]);
            DateTime dtfile = dog.ReadDateFile();
            if (dtfile > dtPc)
            {
                MessageBox.Show("计算机时间不正确，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(-1);
            }

        }

        /// <summary>
        /// 加载主窗体时检查网卡MAC地址
        /// </summary>
        private void CheckNetCardMacAddressOnFormLoad()
        {
            List<string> currentCardMacAddressList = GetNetCardMacAddress();
            string preCardMacAddress = dog.ReadNetCardMacFile();
            if (!currentCardMacAddressList.Contains(preCardMacAddress))
            {
                bool update = false;

                try
                {
                    update = webMethod.UpdateHardware(dogCode);
                }
                catch
                {
                    WriteLogForCheck.WriteLogFile("检查硬件编号更新标志时，外网连接错误" + DateTime.Now.ToString());
                }
                if (update)
                {
                    dog.WriteNetCardMacFile(Encoding.ASCII.GetBytes(currentCardMacAddressList.First()));
                    webMethod.SetOffUpdateHardWare(dogCode);

                }
                else
                {
                    MessageBox.Show("该计算机没有软件运行授权，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Environment.Exit(0);
                }
            }

        }
        /// <summary>
        /// 定时检查网卡MAC地址
        /// </summary>
        private void CheckNetCardMacAddress()
        {
            List<string> currentCardMacAddressList = GetNetCardMacAddress();
            string preCardMacAddress = dog.ReadNetCardMacFile();
            if (!currentCardMacAddressList.Contains(preCardMacAddress))
            {
                if (DateTime.Now.Day != 25)
                {
                    bool update = false;

                    try
                    {
                        update = webMethod.UpdateHardware(dogCode);
                    }
                    catch
                    {
                        WriteLogForCheck.WriteLogFile("检查硬件编号更新标志时，外网连接错误" + DateTime.Now.ToString());
                    }
                    if (update)
                    {
                        dog.WriteNetCardMacFile(Encoding.ASCII.GetBytes(currentCardMacAddressList.First()));
                        webMethod.SetOffUpdateHardWare(dogCode);

                    }
                    else
                    {
                        MessageBox.Show("该计算机没有软件运行授权，无法继续运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Environment.Exit(0);
                    }
                }
            }

        }
        /// <summary> 
        /// 取得设备网卡的MAC地址 
        /// </summary> 
        public List<string> GetNetCardMacAddress()
        {
            List<string> list = new List<string>();
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            string str = "";
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    str = mo["MacAddress"].ToString();
                    list.Add(str);
                }
                    
            }
            return list;
        }
        /// <summary>
        /// 写加密字符串
        /// </summary>
        private void WritePwdStr()
        {
            byte[] bytesdogcode;
            try
            {
                dog.GetDogCode(out bytesdogcode);


                string pwdStr = webMethod.GetPassWordStr(bytesdogcode);
                if (pwdStr != string.Empty)
                {
                    if (CheckPwdstr(pwdStr))
                    {
                        dog.WritePwdStrFile(Encoding.ASCII.GetBytes(pwdStr));
                    }
                    else
                    {
                        WriteLogForCheck.WriteLogFile("校验加密字符串失败  " + DateTime.Now.ToString());
                    }

                }
                else
                {
                    WriteLogForCheck.WriteLogFile("从Webservice上获取的加密字符串为空 " + DateTime.Now.ToString());
                }
            }
            catch (EndpointNotFoundException ex)
            {
                WriteLogForCheck.WriteLogFile("写加密字符串时外网络连接失败  " + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                WriteLogForCheck.WriteLogFile(ex.Message + DateTime.Now.ToString());
            }
        }
        /// <summary>
        /// 校验加密字符串
        /// </summary>
        /// <param name="pwdstr"></param>
        /// <returns></returns>
        private bool CheckPwdstr(string pwdstr)
        {
            bool flag = true;
            int pwdNum = pwdstr.Length / 16;
            for (int i = 0; i < pwdNum; i++)
            {
                string pwd = pwdstr.Substring(i * 16, 8);
                string endogcode = pwdstr.Substring(i * 16 + 8, 8);
                string datadogcode = dog.Decipher(endogcode, pwd);
                if (datadogcode != Encoding.ASCII.GetString(dogCode))
                {
                    flag = false;
                    break;
                }
            }

            return flag;

        }
        /// <summary>
        /// 获得最后到期时间
        /// </summary>
        private void GetLastDate()
        {
            try
            {
                lbLastDate.Text = webMethod.GetLastDate(dogCode);
            }
            catch
            {
                WriteLogForCheck.WriteLogFile("获取最后到期时间失败  " + DateTime.Now.ToString());
            }
        }

        /// <summary>
        /// 每2小时检查一次日期
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerCheckDate_Tick(object sender, EventArgs e)
        {
            CheckDate();
        }

        /// <summary>
        /// 每2个多小时检查一次exe文件MD5码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerCheckExeFile_Tick(object sender, EventArgs e)
        {
            CheckExeMD5();
        }

        /// <summary>
        /// 每天0点获取加密字符串中的加密狗编号的密文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerGetWebEnDogCode_Tick(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            if (dt.Hour == 0)
            {
                if (wsInfo != null)
                {
                    if (wsInfo.AuthorizationDate.AddDays(-30) < DateTime.Now)
                    {
                        SocketMethod.strEnWebDogCode = GetENWebdogcode();
                        WritePwdStr();//写加密字符 串
                    }
                }
                else
                {
                    WriteLogForCheck.WriteLogFile("固定时间写加密字符串失败：没有在webservice中获取到加密狗信息" + DateTime.Now.ToString());
                }

                SetLocalTime();//同步电脑时间，并写日期文件
            }
        }

        /// <summary>
        /// 每2个多小时检查一次网卡MAC地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerCheckNetCardMac_Tick(object sender, EventArgs e)
        {
            //CheckNetCardMacAddress();
        }

        /// <summary>
        /// 检查加密狗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerCheckDog_Tick(object sender, EventArgs e)
        {
            if (dog.GetDogNum() == 0)
            {
                Program._notFoundDog = true;
                thSendMessage.Suspend();
                this.Close();
                timerCheckDog.Enabled = false;
            }
        }

        private void tsbtnGetpwdStrAndLastDate_Click(object sender, EventArgs e)
        {

            try
            {
                wsInfo = webMethod.GetWorkShopInfo(dogCode);
                if (wsInfo != null)
                {
                    lbLastDate.Text = wsInfo.AuthorizationDate.ToShortDateString();
                }
                WritePwdStr();
            }
            catch
            {
                MessageBox.Show("获取最后使用时间失败，原因是连接WebService失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        delegate void ShowSetInfoHander();
        private void ShowSetInfo()
        {
            try
            {

                GetLastDate();
                if (lbDeciperPort.InvokeRequired)
                {
                    Invoke(new ShowSetInfoHander(ShowSetInfo));
                }
                else
                {
                    lbDeciperPort.Text = Properties.Settings.Default.deciperServerPort.ToString();
                }
                if (lbCrcPort.InvokeRequired)
                {
                    Invoke(new ShowSetInfoHander(ShowSetInfo));
                }
                else
                {
                    lbCrcPort.Text = Properties.Settings.Default.OrderCRCServerPort.ToString();
                }

                if (lbServerName.InvokeRequired)
                {
                    Invoke(new ShowSetInfoHander(ShowSetInfo));
                }
                else
                {
                    lbServerName.Text = Properties.Settings.Default.ServerName;
                }
                if (lbDataBaseName.InvokeRequired)
                {
                    Invoke(new ShowSetInfoHander(ShowSetInfo));
                }
                else
                {
                    lbDataBaseName.Text = Properties.Settings.Default.DataBaseName;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("在向界面显示付值时出错!");
            }

        }
        private void tsbtnDataBaseSetting_Click(object sender, EventArgs e)
        {
            FrmDataBaseConnectionString frm = new FrmDataBaseConnectionString();
            frm.dataBaseRefreshHander = new RefreshSetHander(ShowSetInfo);
            frm.ShowDialog();
            if (Program._serverChange)
            {
                if(frmPhoto !=null)
                    frmPhoto.Close();
                if(frmCRCCheck !=null)
                     frmCRCCheck.Close();
                this.Close();
            }
        }

        private void tsbtnSetPort_Click(object sender, EventArgs e)
        {
            FrmPort frmPort = new FrmPort();
            frmPort.portRefreshHander = new RefreshSetHander(ShowSetInfo);
            frmPort.ShowDialog();
        }


        /// <summary>
        /// 每50分钟检查一下前一下小时里有没有完成而没有被移动成功的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tMoveHistoryData_Tick(object sender, EventArgs e)
        {
           
            if (DateTime.Now.Hour == 0 || DateTime.Now.Hour == 2 || DateTime.Now.Hour == 4)
            {
                MINERP.COM.WriteLogForCheck.WriteLogFile(DateTime.Now + "移动数据启动");
                OrderBagBLL.MoveHistoryData();
            }
        }

        private void bwProductTemplete_DoWork(object sender, DoWorkEventArgs e)
        {
            prodctTempleHost._shopList = _orderBLL.GetShopList();
            prodctTempleHost._shopProductTempleteList = _orderBLL.GetAllShopProductTempleteList("厘米");
        }

        private void bwProductTemplete_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lbMsg.Text = "产品加载完成";
        }
        bool _isMarkCompleteRuning = false;
        private void backgroundWorkerMarkComplete_DoWork(object sender, DoWorkEventArgs e)
        {
            _isMarkCompleteRuning = true;
            try
            {
                _orderBLL.MarkOrderBagComplete();
            }
            catch { }
            finally
            {
            _isMarkCompleteRuning = false;
            }
        }

        private void backgroundWorkerMarkComplete_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void backgroundWorkerMarkComplete_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          
        }

        private void timerMarkComplete_Tick(object sender, EventArgs e)
        {
            if (!_isMarkCompleteRuning)
            {
                backgroundWorkerMarkComplete.RunWorkerAsync();
            }

        }

        private void timerChenkOerder_Tick(object sender, EventArgs e)
        {
            if (!_isCheckOrderRunning)
            {
                backgroundWorkerCheckOrder.RunWorkerAsync();
            }
        }
        bool _isCheckOrderRunning = false;
        private void backgroundWorkerCheckOrder_DoWork(object sender, DoWorkEventArgs e)
        {
            _isCheckOrderRunning=true;
            try
            {
                _orderBLL.CheckOrderInfo();
            }
            catch { }
            finally { _isCheckOrderRunning = false; }
          
        }

        private void timerCheckPrintedOrderInfo_Tick(object sender, EventArgs e)
        {
            try
            {
                _orderBLL.CheckPrintedOrderInfo();
            }
            catch { }

        }

    }
}
